package com.sinovatech.ologger.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.sinovatech.ologger.constants.Globals;

public class FileManager {

	public FileManager(long uid, String moduleName) {
		String path = getUserPathReal();
		if (!new File(path).isDirectory()) {
			new File(path).mkdirs();
		}
	}

	public static String getUserPathReal() {
		StringBuffer userPath = new StringBuffer();
		userPath.append(Globals.ATTRIBUTE_UPLOAD_PATH);
		userPath.append(File.separator);
		if (!new File(userPath.toString()).isDirectory()) {
			new File(userPath.toString()).mkdirs();
		}
		return userPath.toString();
	}

	public static void delFile(String location) {
		if (location == null)
			return;
		File f = new File(location);
		if (f.exists()) {
			f.delete();
		}
	}

	public static String saveFile(File file, String destFileName) {
		String path = "";
		OutputStream bos = null;
		InputStream in = null;
		try {
			path = getUserPathReal();
			in = new FileInputStream(file);
			File myFile = new File(path + destFileName);
			File parentFile = myFile.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			bos = new FileOutputStream(myFile);
			int temp = 0;
			byte[] buffer = new byte[8192];
			while ((temp = in.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, temp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return path + destFileName;
	}

}